package cn.yywd_123.akarin.server;

/*
 *  Author: yywd_123
 *  Date: 2022/11/21
 */

import cn.yywd_123.akarin.server.utils.SocketServer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Random;

public class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("请输入服务器端口(0~65536,乱输直接给你随机了): ");
		int port;
		try {
			port = Integer.parseInt(reader.readLine());
			if (port > 65536) port %= 65536;
		} catch (NumberFormatException e) {
			port = new Random().nextInt(65536);
		}
		System.out.print("请输入服务器最大在线人数: ");
		int thread = 20;
		try {
			thread = Integer.parseUnsignedInt(reader.readLine());
		} catch (NumberFormatException ignore) {}

		try (SocketServer server = new SocketServer(port, thread)) {
			server.start();
			String s;
			while (!(s = reader.readLine()).equals("exit")) {
				if (s.equalsIgnoreCase("help"))
					System.out.println("帮助信息:\n" +
							"  help                  显示此帮助信息\n" +
							"  info                  显示服务器状态\n" +
							"  msg <消息>             发送一条消息\n" +
							"  mute <用户> [时间+单位] 将用户禁言,不填时间则取消禁言(时间单位有h,m和s)\n" +
							"  ban <用户名>           禁止该用户名加入服务器(再次运行可撤销)\n" +
							"  banip <ip地址>         禁止此ip的用户加入服务器(再次运行可撤销)\n" +
							"  kick <用户名>          将用户踢出服务器\n" +
							"\n" +
							"  exit                  关闭服务器");
				if (s.equalsIgnoreCase("info")) server.showServerInfo();
				if (s.split(" ", 2)[0].equalsIgnoreCase("msg")) {
					String str = s.split(" ", 2)[1];
					if (!str.isEmpty()) server.sendMessageToAllClient(str, null);
					else System.out.println("请输入信息!");
				}
				if (s.split(" ", 2)[0].equalsIgnoreCase("mute")) {
					String str = s.split(" ", 2)[1];
					if (!str.isEmpty()) {
						String[] arg = str.split(" ", 2);
						server.getUserManager().muteUser(arg[0], arg[1]);
					} else System.out.println("请输入用户名称!");
				}
				if (s.split(" ", 2)[0].equalsIgnoreCase("ban")) {
					String str = s.split(" ", 2)[1];
					if (!str.isEmpty()) {
						server.getUserManager().banUser(str);
					} else System.out.println("请输入用户名称!");
				}
				if (s.split(" ", 2)[0].equalsIgnoreCase("banip")) {
					String str = s.split(" ", 2)[1];
					if (!str.isEmpty()) {
						server.getUserManager().banIp(str);
					} else System.out.println("请输入ip地址!");
				}
				if (s.split(" ", 2)[0].equalsIgnoreCase("kick")) {
					String str = s.split(" ", 2)[1];
					if (!str.isEmpty()) {
						server.getUserManager().kick(str);
					} else System.out.println("请输入用户名!");
				}
			}
			System.exit(0);
		}
	}
}
